<template>
  <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
    <el-form-item label="货源编号" prop="goodsSourceNo">
      <el-input clearable :maxlength="50" v-model="queryParams.goodsSourceNo" placeholder="请输入货源编号"
        @keyup.enter="handleQuery" class="!w-200px" />
    </el-form-item>
    <el-form-item label="货源名称" prop="goodsSourceName">
      <el-input clearable :maxlength="50" v-model="queryParams.goodsSourceName" placeholder="请输入货源名称"
        @keyup.enter="handleQuery" class="!w-200px" />
    </el-form-item>
    <el-form-item label="失效时间" prop="failureTime">
      <el-date-picker v-model="queryParams.failureTime " value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始时间"
        end-placeholder="结束时间" type="datetimerange" class="!w-400px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery">
        搜索
      </el-button>
      <el-button @click="resetQuery">
        重置
      </el-button>
    </el-form-item>
  </el-form>
  <el-radio-group v-model="current" class="mb-16px" @change="radioChange">
    <el-radio-button :value="item" :label="item" v-for="item in statusList" :key="item" />
  </el-radio-group>
  <el-table v-loading="loading" :data="list" border stripe
    :header-cell-style="{ background: '#F3F4F7', color: '#555' }">
    <el-table-column label="货源编号" align="center" prop="goodsSourceNo" min-width="200" fixed="left"
      :show-overflow-tooltip="true">
      <template #default="{ row }">
        <span style="color: #409eff;cursor:pointer" @click="openDetailDialog(row.id)">{{row.goodsSourceNo}}</span>
      </template>
    </el-table-column>
    <el-table-column label="业务类型" align="center" prop="bizType" min-width="100" :show-overflow-tooltip="true">
      <template #default="{ row }">
        {{getDictLabel(DICT_TYPE.BIZ_TYPE, row.bizType?.toString())}}
      </template>
    </el-table-column>
    <el-table-column label="货源名称" align="center" prop="goodsSourceName" min-width="150" :show-overflow-tooltip="true" />
    <el-table-column label="状态" align="center" prop="status" min-width="100" :show-overflow-tooltip="true">
      <template #default="{ row }">
        {{getDictLabel(DICT_TYPE.GOODS_SOURCE, row.status?.toString())}}
      </template>
    </el-table-column>
    <el-table-column label="装货地" align="left" prop="loadingPlaceName" min-width="250">
      <template #default="{ row }">
        <div>{{row.loadingPlaceName}}</div>
        <div>{{row.address}}</div>
      </template>
    </el-table-column>
    <el-table-column label="卸货地" align="left" prop="unloadingPlaceName" min-width="250">
      <template #default="{ row }">
        <div>{{row.unloadingPlaceName}}</div>
        <div>{{row.unloadingPlaceAddress}}</div>
      </template>
    </el-table-column>
    <el-table-column label="运价" align="center" prop="freight" min-width="100" :show-overflow-tooltip="true">
    </el-table-column>
    <el-table-column label="产品" align="center" prop="productName" min-width="150" :show-overflow-tooltip="true" />
    <el-table-column label="结算依据" align="center" prop="settlementBasis" min-width="100" :show-overflow-tooltip="true">
      <template #default="{ row }">
        {{getDictLabel(DICT_TYPE.SETTLEMENT_BASIS, row.settlementBasis?.toString())}}
      </template>
    </el-table-column>
    <el-table-column label="是否计算路损" align="center" prop="isCalculateRoadLoss" min-width="150"
      :show-overflow-tooltip="true">
      <template #default="{ row }">
        {{getDictLabel(DICT_TYPE.IS_CALCULATE_ROAD_LOSS, row.isCalculateRoadLoss?.toString())}}
      </template>
    </el-table-column>
    <el-table-column label="路损单价" align="center" prop="roadLossPrice" min-width="100" :show-overflow-tooltip="true" />
    <el-table-column label="合理路损" align="center" prop="reasonableRoadLoss" min-width="100"
      :show-overflow-tooltip="true" />
    <el-table-column label="生效时间" align="center" prop="startTime" min-width="200" :show-overflow-tooltip="true" />
    <el-table-column label="失效时间" align="center" prop="endTime" min-width="200" :show-overflow-tooltip="true" />
    <el-table-column label="备注" align="center" prop="remark" min-width="200" :show-overflow-tooltip="true" />
    <el-table-column label="三方单号" align="center" prop="planNo" min-width="200" :show-overflow-tooltip="true" />
    <el-table-column label="数据来源" align="center" prop="dataSource" min-width="150" :show-overflow-tooltip="true">
      <template #default="{ row }">
        {{getDictLabel(DICT_TYPE.DATA_SOURCE, row.dataSource?.toString())}}
      </template>
    </el-table-column>
    <el-table-column label="创建时间" align="center" prop="createTime" min-width="200" :show-overflow-tooltip="true" />
    <el-table-column label="操作" align="center" width="220" fixed="right">
      <template #default="{ row }">
        <el-container class="operate-box">
          <span v-hasPermi="['goodsSource:orderCode']">
            <el-button v-if="row.orderAcceptanceCodeBtn" type="primary" link
              @click="openQrcodeDialog(row.id)">接单码</el-button>
          </span>
          <span v-hasPermi="['goodsSource:findCar']">
            <el-button v-if="row.findVehicleBtn" type="primary" link @click="findTrainFn(row)">找车</el-button>
          </span>
          <span v-hasPermi="['goodsSource:edit','goodsSource:finish', 'goodsSource:cancel']">
            <el-dropdown @command="(command) => handleCommand(command, row)"
              v-if="row.editBtn && row.completeBtn && row.cancelBtn">
              <el-button type="primary" link>
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-container v-hasPermi="['goodsSource:edit']">
                    <el-dropdown-item v-if="row.editBtn" command="edit">
                      <el-button type="primary" link>
                        编辑
                      </el-button>
                    </el-dropdown-item>
                  </el-container>
                  <el-container v-hasPermi="['goodsSource:finish']">
                    <el-dropdown-item v-if="row.completeBtn" command="finish">
                      <el-button type="primary" link>
                        完成
                      </el-button>
                    </el-dropdown-item>
                  </el-container>
                  <el-container v-hasPermi="['goodsSource:cancel']">
                    <el-dropdown-item v-if="row.cancelBtn" command="cancel">
                      <el-button type="primary" link>
                        作废
                      </el-button>
                    </el-dropdown-item>
                  </el-container>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </span>
        </el-container>
      </template>
    </el-table-column>
  </el-table>
  <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
    @pagination="getList" />
  <GoodsSourceForm ref="goodsSourceFormRef" @success="resetQuery"></GoodsSourceForm>
  <GoodsSourceDetail ref="goodsSourceDetailRef"></GoodsSourceDetail>
  <QrCodeDialog ref="qrCodeDialogRef"></QrCodeDialog>
</template>
<script lang="ts" setup name="goodsSourceList">
  import { DICT_TYPE, getIntDictOptions, getDictLabel } from '@/utils/dict'
  import * as goodsSourceApi from '@/api/transportation/goodsSource'
  import { useCommonStoreOut } from '@/store/modules/common'
  import GoodsSourceDetail from './goodsSourceDetail.vue'
  import GoodsSourceForm from './goodsSourceForm.vue'
  import QrCodeDialog from './qrCodeDialog.vue'
  import { cloneDeep } from 'lodash'

  const useCommonStore = useCommonStoreOut()
  const emit = defineEmits(['subPage'])
  const goodsSourceDetailRef = ref()
  const goodsSourceFormRef = ref()
  const qrCodeDialogRef = ref()
  const queryFormRef = ref()
  const message = useMessage()
  const current = ref()
  const list = ref([])
  const total = ref(0)
  const statusList = ref([])
  const loading = ref(false)
  let statusMap = {}
  const queryParams = ref({
    goodsSourceNo: undefined,
    goodsSourceName: undefined,
    failureTime: [],
    pageNo: 1,
    pageSize: 10,
  })

  const getStatusList = () => {
    const result = {}
    statusList.value = ['全部']
    statusMap = { 全部: undefined }
    const options = getIntDictOptions(DICT_TYPE.GOODS_SOURCE)
    options.forEach(e => result[e.label] = e.value)
    statusList.value = [...statusList.value, ...options.map(e => e.label)]
    statusMap = { ...statusMap, ...result }
    current.value = statusList.value.includes('已发布') ? '已发布' : '全部'
  }

  const radioChange = (tab) => {
    handleQuery()
  }

  const getList = async () => {
    loading.value = true
    try {
      const data = cloneDeep(queryParams.value)
      if (statusMap[current.value]) {
        data['status'] = statusMap[current.value]
      }
      const res = await goodsSourceApi.getGoodsSourcePage(data)
      list.value = res.list || []
      total.value = res.total || 0
    } finally {
      loading.value = false
    }
  }

  const handleQuery = () => {
    queryParams.value.pageNo = 1
    getList()
  }

  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  const findTrainFn = async (row) => {
    await goodsSourceApi.getGoodsSource({ id: row.id })
    useCommonStore.setFormData({ id: row.id, bizType: row.bizType, loadingPlaceProvinceCode: row.loadingPlaceProvinceCode, loadingPlaceCityCode: row.loadingPlaceCityCode, loadingPlaceCountyCode: row.loadingPlaceCountyCode, loadingPlaceTownCode: row.loadingPlaceTownCode, unloadingPlaceProvinceCode: row.unloadingPlaceProvinceCode, unloadingPlaceCityCode: row.unloadingPlaceCityCode, unloadingPlaceCountyCode: row.unloadingPlaceCountyCode, unloadingPlaceTownCode: row.unloadingPlaceTownCode })
    emit('subPage', 1)
  }

  const handleCommand = (type, row) => {
    switch (type) {
      case 'edit':
        openFormDialog(row.id)
        break;
      case 'finish':
        handleFinish(row.id)
        break;
      case 'cancel':
        handleCancel(row.id)
    }
  }

  const openDetailDialog = (id) => {
    goodsSourceDetailRef.value.open(id)
  }

  const openFormDialog = async (id) => {
    await goodsSourceApi.getGoodsSource({ id })
    goodsSourceFormRef.value.open(id)
  }

  const openQrcodeDialog = async (id) => {
    const data = await goodsSourceApi.getGoodsSource({ id })
    qrCodeDialogRef.value.open(data)
  }

  const handleFinish = async (id) => {
    await message.confirm('您确认完成该货源吗？')
    await goodsSourceApi.completeGoodsSource({
      id, operatingPlatform: 2
    })
    message.success('操作成功')
    resetQuery()
  }

  const handleCancel = async (id) => {
    await message.confirm('您确认作废该货源吗？')
    await goodsSourceApi.cancelGoodsSource({ id })
    message.success('操作成功')
    resetQuery()
  }

  onMounted(() => {
    getStatusList()
    getList()
  })
</script>
<style lang="scss" scoped>
  :deep(.el-radio-button__inner) {
    padding: 8px 24px;
    background-color: #EFF1F3;
  }

  .operate-box {
    .el-button.is-link {
      padding: 0 !important;
    }

    .el-dropdown {
      vertical-align: middle
    }

    >span {
      padding: 0 16px;
      line-height: 13px;
      border-right: 1px solid #D9D9D9;
    }

    >:last-child {
      border-right: none
    }
  }
</style>